/**
 * Copyright (C) 2022-2023
 * All rights reserved, Designed By www.tonetn.com
 * 注意：
 * 本软件为www.tonetn.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package com.xunyin.modules.recharge.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.dozer.service.IGenerator;
import com.xunyin.enums.ResultFlag;
import com.xunyin.modules.log.domain.TimelongRecord;
import com.xunyin.modules.log.service.mapper.TimelongRecordMapper;
import com.xunyin.modules.members.domain.TMembers;
import com.xunyin.modules.members.service.mapper.TMembersMapper;
import com.xunyin.modules.membersuser.domain.TMembersUser;
import com.xunyin.modules.membersuser.service.mapper.TMembersUserMapper;
import com.xunyin.modules.membersuser.vo.MemberUserVo;
import com.xunyin.modules.recharge.domain.TRechargeOrder;
import com.xunyin.modules.recharge.domain.TRechargeSet;
import com.xunyin.modules.recharge.service.TRechargeOrderService;
import com.xunyin.modules.recharge.service.dto.TRechargeOrderDto;
import com.xunyin.modules.recharge.service.dto.TRechargeOrderQueryCriteria;
import com.xunyin.modules.recharge.service.mapper.TRechargeOrderMapper;
import com.xunyin.modules.recharge.service.mapper.TRechargeSetMapper;
import com.xunyin.modules.recharge.vo.TRechargeOrderVo;
import com.xunyin.modules.shareorder.service.dto.OrderStatDto;
import com.xunyin.modules.store.domain.TStore;
import com.xunyin.modules.store.service.TStoreService;
import com.xunyin.modules.user.domain.SysXbAppUser;
import com.xunyin.modules.user.service.mapper.SysXbAppUserMapper;
import com.xunyin.utils.CommonConst;
import com.xunyin.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


/**
 * @Author xunyinyunshang  <3594419785@qq.com>
 * @date 2022-10-12
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TRechargeOrderServiceImpl extends BaseServiceImpl<TRechargeOrderMapper, TRechargeOrder> implements TRechargeOrderService {

    private final IGenerator generator;

    @Autowired
    private TRechargeOrderMapper tRechargeOrderMapper;

    @Autowired
    private TRechargeSetMapper tRechargeSetMapper;

    @Autowired
    private SysXbAppUserMapper sysXbAppUserMapper;

    @Autowired
    private TStoreService tStoreService;

    @Autowired
    private TMembersUserMapper tMembersUserMapper;

    @Autowired
    private TMembersMapper tMembersMapper;

    @Autowired
    private TimelongRecordMapper timelongRecordMapper;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(TRechargeOrderQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<TRechargeOrder> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<TRechargeOrder> queryAll(TRechargeOrderQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(TRechargeOrder.class, criteria));
    }

    /**
     * 获取优惠套餐订单统计数据
     * @return OrderStatDto
     */
    @Override
    public OrderStatDto getOrderStatForRecharge() {
        OrderStatDto orderStatDto = new OrderStatDto();
        orderStatDto.setSumOrderMoney(tRechargeOrderMapper.sumOrderMoney());
        orderStatDto.setSumRealOrderMoney(tRechargeOrderMapper.sumRealOrderMoney());
        return orderStatDto;
    }

    /**
     * 充值订单管理
     * @return List<TRechargeOrderVo>
     */
    @Override
    public List<TRechargeOrderVo> getRechargeOrderByTeaHouseId(Integer teahouseId) {
        log.info("[getRechargeOrderByTeaHouseId].teahouseId={}", teahouseId);
        return tRechargeOrderMapper.getRechargeOrderByTeaHouseId(teahouseId);
    }

    /**
     * 根据订单号获取订单信息
     * @param appOrderNo
     * @return
     */
    @Override
    public TRechargeOrder selectByAppOrderNo(String appOrderNo) {
        LambdaQueryWrapper<TRechargeOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(i -> i.eq(TRechargeOrder::getAppOrderNo, appOrderNo));
        wrapper.and(i -> i.eq(TRechargeOrder::getStatus, 1));
        return tRechargeOrderMapper.selectOne(wrapper);
    }

    /**
     * 充值订单支付完成回调
     * @param rechargeOrder
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargeOrderPayNotify(TRechargeOrder rechargeOrder) {
        log.info("=====充值订单支付完成回调=====");
        try {
            TRechargeOrder updateStRechargeOrder = new TRechargeOrder();
            updateStRechargeOrder.setId(rechargeOrder.getId());
            updateStRechargeOrder.setResultFlag(ResultFlag.PAID.getValue());
            updateStRechargeOrder.setPayTime(new Date());

            updateStRechargeOrder.setTransactionId(rechargeOrder.getTransactionId());
            updateStRechargeOrder.setUpdateTime(new Date());
            updateStRechargeOrder.setOrderStatus(CommonConst.ENABLE_FLAG);

            LambdaQueryWrapper<TRechargeOrder> wrappers = new LambdaQueryWrapper<>();
            wrappers.eq(TRechargeOrder::getId, rechargeOrder.getId());

            tRechargeOrderMapper.update(updateStRechargeOrder, wrappers);

            log.info("订单修改成功,支付订单号：{}", rechargeOrder.getAppOrderNo());

            log.info("支付成功，开始给账户充值");
            TRechargeSet stRechargeSet = tRechargeSetMapper.selectById(rechargeOrder.getRechargeSetId());

            SysXbAppUser stAppUser = new SysXbAppUser();
/*                stAppUser.setAppId(rechargeOrder.getAppUserId());
                stAppUser.setStatus(CommonConst.ENABLE_FLAG);*/
            LambdaQueryWrapper<SysXbAppUser> wrapperAppUser = new LambdaQueryWrapper<>();
            wrapperAppUser.eq(SysXbAppUser::getAppId, rechargeOrder.getAppUserId());
            wrapperAppUser.eq(SysXbAppUser::getStatus, CommonConst.ENABLE_FLAG);
            List<SysXbAppUser> list = sysXbAppUserMapper.selectList(wrapperAppUser);
            if (list != null && list.size() > 0) {
                stAppUser = list.get(0);
            }
            Integer teaHouseId = stRechargeSet.getTeaHouseId();
            //JSONObject tea = teaHouseDao.getTeaInfoById(teaHouseId);
            TStore tStore = tStoreService.getById(teaHouseId);
            Integer mainId = tStore.getMainId();
            //TeaMembersUser teaMembersUser = teaMembersUserMapper.selectByTransPhoneAndMainId(stAppUser.getTelephone(), mainId);
            MemberUserVo memberUserVo = tMembersUserMapper.selectByTransPhoneAndMainId(stAppUser.getTelephone(), mainId);
            TMembersUser teaMembersUser = new TMembersUser();
            BeanUtil.copyProperties(memberUserVo, teaMembersUser);

            // 根据会员级别与主体ID获取会员等级信息
            LambdaQueryWrapper<TMembers> wrapperMember = new LambdaQueryWrapper<>();
            wrapperMember.eq(TMembers::getMembersLevel, Integer.parseInt(stRechargeSet.getLevel().toString()));
            wrapperMember.eq(TMembers::getMainId, stRechargeSet.getMainId());
            //TMembers members = tMembersMapper.selectOne(wrapperMember);
            List<TMembers> membersList = tMembersMapper.selectList(wrapperMember);

            Integer membersId = 0;
            if (membersList != null && membersList.size() > 0) {
                membersId = membersList.get(0).getId();
            }

            if (teaMembersUser == null) {
                teaMembersUser = new TMembersUser();
                teaMembersUser.setMainId(mainId);
                //teaMembersUser.setMembersId(stAppUser.getId());
                teaMembersUser.setMembersTimeLength(BigDecimal.valueOf(stRechargeSet.getTimeLong()));
                teaMembersUser.setMemberUserPhone(stAppUser.getTelephone());
                teaMembersUser.setUpdateTime(new Date());
                teaMembersUser.setStatus(CommonConst.ENABLE_FLAG);
                teaMembersUser.setMembersTransCount(0);
                teaMembersUser.setMembersId(membersId);
                tMembersUserMapper.insert(teaMembersUser);
            } else {

                teaMembersUser.setMembersId(membersId);
                BigDecimal membersTimeLength = teaMembersUser.getMembersTimeLength().add(BigDecimal.valueOf(stRechargeSet.getTimeLong()));
                teaMembersUser.setMembersTimeLength(membersTimeLength);
                teaMembersUser.setUpdateTime(new Date());
                // 根据会员用户Id,更新会员用户的可使用预约时长
                LambdaQueryWrapper<TMembersUser> wrapperMemberUser = new LambdaQueryWrapper<>();
                wrapperMemberUser.eq(TMembersUser::getId, teaMembersUser.getId());
                tMembersUserMapper.update(teaMembersUser, wrapperMemberUser);

                //teaMembersUserMapper.updateByPrimaryKeySelective(teaMembersUser);
            }

            //记录时长使用日志
            TimelongRecord timelongRecord = new TimelongRecord();
            timelongRecord.setMainId(mainId);
            timelongRecord.setSource(4);
            timelongRecord.setTimelong(BigDecimal.valueOf(stRechargeSet.getTimeLong()));
            timelongRecord.setGiver(stAppUser.getId());
            timelongRecord.setRecipient(0);
            timelongRecord.setOrderNo(rechargeOrder.getAppOrderNo());
            timelongRecord.setRemark("订单支付-部分使用时长");
            timelongRecord.setCreateUserId(0);
            timelongRecord.setCreateTime(new Date());
            timelongRecord.setStatus(Short.parseShort("1"));
            timelongRecordMapper.insert(timelongRecord);

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public void download(List<TRechargeOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TRechargeOrderDto tRechargeOrder : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("主体Id", tRechargeOrder.getMainId());
            map.put("门店Id", tRechargeOrder.getTeaHouseId());
            map.put("门店名称", tRechargeOrder.getTeaHouseName());
            map.put("下单时间", tRechargeOrder.getOrderTime());
            map.put("微信订单号", tRechargeOrder.getTransactionId());
            map.put("订单号", tRechargeOrder.getOrderNo());
            map.put("应用用户ID(微信openid,支付宝userid)", tRechargeOrder.getAppUserId());
            map.put("应用类型", tRechargeOrder.getAppType());
            map.put("优惠套餐Id", tRechargeOrder.getRechargeSetId());
            map.put("产品名称", tRechargeOrder.getRechargeSetName());
            map.put("支付订单号", tRechargeOrder.getAppOrderNo());
            map.put("支付结果", tRechargeOrder.getResultFlag());
            map.put("支付时间", tRechargeOrder.getPayTime());
            map.put("支付方式", tRechargeOrder.getPayType());
            map.put("订单金额", tRechargeOrder.getOrderMoney());
            map.put("支付金额", tRechargeOrder.getPayMoney());
            map.put("总优惠额度", tRechargeOrder.getAllDiscountMoney());
            map.put("会员用户Id", tRechargeOrder.getMembersUserId());
            map.put("会员折扣", tRechargeOrder.getMembersDiscount());
            map.put("退款订单号", tRechargeOrder.getRefundOrderNo());
            map.put("退款应用订单号", tRechargeOrder.getRefundAppOrderNo());
            map.put("退款时间", tRechargeOrder.getRefundTime());
            map.put("退款金额", tRechargeOrder.getRefundMoney());
            map.put("退款状态", tRechargeOrder.getReturnFlag());
            map.put("错误代码", tRechargeOrder.getErrCode());
            map.put("错误代码描述", tRechargeOrder.getErrCodeDesc());
            map.put("页面ID", tRechargeOrder.getPageId());
            map.put("是否结算", tRechargeOrder.getSettleFlag());
            map.put("备注", tRechargeOrder.getRemark());
            map.put("订单状态(0：待支付 1：已支付  2：已取消 3：已完成  4：已退款)", tRechargeOrder.getOrderStatus());
            map.put("创建日期", tRechargeOrder.getCreateTime());
            map.put("更新日期", tRechargeOrder.getUpdateTime());
            map.put("删除日期", tRechargeOrder.getDeleteTime());
            map.put("创建用户ID", tRechargeOrder.getCreateUserId());
            map.put("更新用户ID", tRechargeOrder.getUpdateUserId());
            map.put("订单状态", tRechargeOrder.getStatus());
            map.put("用户手机号码", tRechargeOrder.getPhone());
            map.put(" isDel", tRechargeOrder.getIsDel());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
